{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "def greet(name):  \n",
    "    \"\"\"返回欢迎信息（功能注释）\"\"\"  \n",
    "    return f\"Hello, {name}!\"  \n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello, name!\n"
     ]
    }
   ],
   "source": [
    "# 调用示例  \n",
    "print(greet(\"DeepSeek\"))  # Hello, DeepSeek!  \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "返回欢迎信息（功能注释）\n"
     ]
    }
   ],
   "source": [
    "print(greet.__doc__)      # 返回欢迎信息（功能注释）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "def greet2(name):  \n",
    "    return f\"Hello, {name}!\"  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Hello, Deepseek!'"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "greet2('Deepseek')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "None\n"
     ]
    }
   ],
   "source": [
    "print(greet2.__doc__) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on function greet in module __main__:\n",
      "\n",
      "greet(name)\n",
      "    返回欢迎信息（功能注释）\n",
      "\n"
     ]
    }
   ],
   "source": [
    "help(greet)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. 避免可变默认值陷阱  \n",
    "def append_value(value, lst=None):  \n",
    "    \"\"\"正确方式：用None作为默认值\"\"\"  \n",
    "    if lst is None:  \n",
    "        lst = []  \n",
    "    lst.append(value)  \n",
    "    return lst  \n",
    "\n",
    "# 2. 类型提示（Python 3.5+）  \n",
    "from typing import List, Dict  \n",
    "\n",
    "def process_data(data: List[str], config: Dict[str, int] = {}) -> float:  \n",
    "    \"\"\"清晰的类型注解\"\"\"  \n",
    "    return 0.0  \n",
    "\n",
    "# 3. 参数验证装饰器  \n",
    "def validate_input(func):  \n",
    "    def wrapper(num: int):  \n",
    "        if not isinstance(num, int):  \n",
    "            raise TypeError(\"必须输入整数\")  \n",
    "        return func(num)  \n",
    "    return wrapper  \n",
    "\n",
    "@validate_input  \n",
    "def square(n):  \n",
    "    return n ** 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "空数据输入\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "def process_data(raw_data):\n",
    "    \"\"\"处理数据并返回多个计算结果\"\"\"\n",
    "    if not raw_data:\n",
    "        print(\"空数据输入\")\n",
    "        return  # 隐式返回None\n",
    "    \n",
    "    sum_val = sum(raw_data)\n",
    "    avg_val = sum_val / len(raw_data)\n",
    "    return sum_val, avg_val  # 显式返回元组\n",
    "\n",
    "# 结果接收方式\n",
    "data = [85, 92, 78]\n",
    "result = process_data(data)           # 接收元组 → (255, 85.0)\n",
    "total, average = process_data(data)  # 分别解包 → total=255, average=85.0\n",
    "\n",
    "# 特殊返回情况\n",
    "print(process_data([]))  # 输出: None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 基本数值处理\n",
    "numbers = [1, 2, 3, 4]\n",
    "squared = map(lambda x: x**2, numbers)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3, 4]\n"
     ]
    }
   ],
   "source": [
    "squared = []\n",
    "for i in [1, 2, 3, 4]:\n",
    "    squared.append(i)\n",
    "\n",
    "print(squared)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 4, 9, 16]\n"
     ]
    }
   ],
   "source": [
    "squared = [x**2 for x in [1,2,3,4]]\n",
    "print(squared)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "702 ms ± 21.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
     ]
    }
   ],
   "source": [
    "%%timeit\n",
    "squared = []\n",
    "for i in range(10000000):\n",
    "    squared.append(i**2)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "653 ms ± 30.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
     ]
    }
   ],
   "source": [
    "%%timeit\n",
    "squared = [x**2 for x in range(10000000)]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1.04 s ± 33.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
     ]
    }
   ],
   "source": [
    "%%timeit\n",
    "\n",
    "squared = list(map(lambda x: x**2, range(10000000)))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 基本数值处理\n",
    "numbers = [1, 2, 3, 4]\n",
    "squared = map(lambda x: x**2, numbers)\n",
    "print(list(squared))  # [1, 4, 9, 16]\n",
    "\n",
    "# 多序列映射计算\n",
    "base = [10, 20]\n",
    "bonus = [3, 5]\n",
    "total = map(lambda a,b: a + b/100, base, bonus)\n",
    "print(list(total))    # [10.03, 20.05]\n",
    "\n",
    "# 类型转换应用\n",
    "str_nums = [\"3.14\", \"-5\", \"100\"]\n",
    "real_nums = map(float, str_nums)\n",
    "print(list(real_nums))  # [3.14, -5.0, 100.0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0, 2, 4, 6, 8]\n",
      "['Apple', 'Cherry']\n",
      "[5, 'text']\n"
     ]
    }
   ],
   "source": [
    "# 基本元素筛选\n",
    "nums = range(10)\n",
    "even = filter(lambda x: x%2 == 0, nums)\n",
    "print(list(even))  # [0,2,4,6,8]\n",
    "\n",
    "# 嵌套条件筛选\n",
    "def is_valid(word):\n",
    "    return len(word) > 3 and word.istitle()\n",
    "\n",
    "words = [\"Apple\", \"box\", \"Cherry\", \"dog\"]\n",
    "valid_words = filter(is_valid, words)\n",
    "print(list(valid_words))  # ['Apple', 'Cherry']\n",
    "\n",
    "# 特殊值过滤\n",
    "mixed = [0, False, \"\", None, 5, \"text\"]\n",
    "truthy = filter(None, mixed)  # 过滤假值\n",
    "print(list(truthy))  # [5, 'text']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['Bob', 'Alice', 'Charlie']\n",
      "[{'name': 'Li', 'salary': 12000}, {'name': 'Wang', 'salary': 8500}]\n",
      "[('Wang', 90), ('Li', 85), ('Zhang', 85)]\n"
     ]
    }
   ],
   "source": [
    "# 基础排序\n",
    "names = [\"Alice\", \"Bob\", \"Charlie\"]\n",
    "print(sorted(names, key=len))  # ['Bob', 'Alice', 'Charlie']\n",
    "\n",
    "# 复杂对象排序\n",
    "employees = [\n",
    "    {\"name\": \"Wang\", \"salary\": 8500},\n",
    "    {\"name\": \"Li\", \"salary\": 12000}\n",
    "]\n",
    "print(sorted(employees, key=lambda x: x[\"salary\"], reverse=True))\n",
    "\n",
    "# 多级排序策略\n",
    "students = [(\"Li\", 85), (\"Zhang\", 85), (\"Wang\", 90)]\n",
    "print(sorted(students, key=lambda x: (-x[1], x[0])))\n",
    "# 成绩降序，姓名升序排列"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "有效成绩排序结果: [100, 92, 85]\n"
     ]
    }
   ],
   "source": [
    "# 数据处理管道：map -> filter -> sorted\n",
    "data = [\"Grade:85\", \"Grade:92\", \"Grade:100\"]\n",
    "\n",
    "# 步骤分解：\n",
    "processed = map(lambda s: s.split(\":\")[1], data)          # ['85', 'invalid', '92', '100A']\n",
    "cleaned = filter(str.isdigit, processed)                  # ['85', '92']\n",
    "scores = sorted(map(int, cleaned), reverse=True)           # [92, 85]\n",
    "\n",
    "print(\"有效成绩排序结果:\", scores)\n",
    "\n",
    "# 使用推导式实现同样功能对比\n",
    "alt_scores = sorted(\n",
    "    [int(s.split(\":\")[1]) \n",
    "     for s in data \n",
    "     if s.split(\":\")[1].isdigit()][::-1]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5.0\n"
     ]
    }
   ],
   "source": [
    "# 基础导入方式\n",
    "import math\n",
    "print(math.sqrt(25))  # 5.0\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "-0.13235175009777303"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import math\n",
    "a = 25\n",
    "math.sin(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10\n"
     ]
    }
   ],
   "source": [
    "# 别名导入\n",
    "import random as rd\n",
    "print(rd.randint(1, 10))  # 生成1-10随机整数\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 选择性导入\n",
    "from math import pi, cos\n",
    "print(cos(pi))  # -1.0\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 文本文件三种常用读写模式\n",
    "MODES = {\n",
    "    'r': '读取（默认模式）',\n",
    "    'w': '写入（覆盖）', \n",
    "    'a': '追加',\n",
    "    'r+': '读写模式'\n",
    "}\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 标准操作流程建议\n",
    "def write_log(filename):\n",
    "    \"\"\"文件写入最佳实践\"\"\"\n",
    "    f = open(filename, 'w', encoding='utf-8')\n",
    "    f.write(\"==== 系统日志 ====\\n\")\n",
    "    f.writelines([f\"事件{i}: 已记录\\n\" for i in range(3)])\n",
    "    f.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 标准操作流程建议\n",
    "def write_log(filename):\n",
    "    \"\"\"文件写入最佳实践\"\"\"\n",
    "    with open(filename, 'w', encoding='utf-8') as f:\n",
    "        f.write(\"==== 系统日志 ====\\n\")\n",
    "        f.writelines([f\"事件{i}: 已记录\\n\" for i in range(10)])\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 执行演示\n",
    "write_log('system.log')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "==== 系统日志 ====\n",
      "事件0: 已记录\n",
      "事件1: 已记录\n",
      "事件2: 已记录\n",
      "事件3: 已记录\n",
      "事件4: 已记录\n",
      "事件5: 已记录\n",
      "事件6: 已记录\n",
      "事件7: 已记录\n",
      "事件8: 已记录\n",
      "事件9: 已记录\n"
     ]
    }
   ],
   "source": [
    "def read_log(filename):\n",
    "    \"\"\"多种读取方式对比\"\"\"\n",
    "    with open(filename, 'r', encoding='utf-8') as f:\n",
    "        # 方法1 全内容读取\n",
    "        # content = f.read()\n",
    "        \n",
    "        # 方法2 行读取优化\n",
    "        for line in f:\n",
    "            print(line.strip())\n",
    "            \n",
    "        # 方法3 按块读取（适合大文件）\n",
    "        # while True:\n",
    "        #     chunk = f.read(4096)\n",
    "        #     if not chunk: break\n",
    "        #     process(chunk)\n",
    "\n",
    "\n",
    "read_log('system.log')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "ename": "OSError",
     "evalue": "[Errno 22] Invalid argument: '--f=c:\\\\Users\\\\zhoux\\\\AppData\\\\Roaming\\\\jupyter\\\\runtime\\\\kernel-v3dd56281ee2a79bb7a4dc5ec7e831f47e0494a325.json'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mOSError\u001b[0m                                   Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[40], line 64\u001b[0m\n\u001b[0;32m     61\u001b[0m     \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m用法: python word_freq.py 小说文件路径\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m     62\u001b[0m     exit(\u001b[38;5;241m1\u001b[39m)\n\u001b[1;32m---> 64\u001b[0m main(sys\u001b[38;5;241m.\u001b[39margv[\u001b[38;5;241m1\u001b[39m])\n",
      "Cell \u001b[1;32mIn[40], line 42\u001b[0m, in \u001b[0;36mmain\u001b[1;34m(file_path)\u001b[0m\n\u001b[0;32m     40\u001b[0m \u001b[38;5;250m\u001b[39m\u001b[38;5;124;03m\"\"\"主流程控制函数\"\"\"\u001b[39;00m\n\u001b[0;32m     41\u001b[0m \u001b[38;5;66;03m# 数据准备阶段\u001b[39;00m\n\u001b[1;32m---> 42\u001b[0m raw_text \u001b[38;5;241m=\u001b[39m read_novel(file_path)\n\u001b[0;32m     43\u001b[0m cleaned_text \u001b[38;5;241m=\u001b[39m clean_text(raw_text)\n\u001b[0;32m     45\u001b[0m \u001b[38;5;66;03m# 分析配置选项\u001b[39;00m\n",
      "Cell \u001b[1;32mIn[40], line 7\u001b[0m, in \u001b[0;36mread_novel\u001b[1;34m(file_path)\u001b[0m\n\u001b[0;32m      5\u001b[0m \u001b[38;5;250m\u001b[39m\u001b[38;5;124;03m\"\"\"读取并返回小说文本内容\"\"\"\u001b[39;00m\n\u001b[0;32m      6\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[1;32m----> 7\u001b[0m     \u001b[38;5;28;01mwith\u001b[39;00m \u001b[38;5;28mopen\u001b[39m(file_path, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mr\u001b[39m\u001b[38;5;124m'\u001b[39m, encoding\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mutf-8\u001b[39m\u001b[38;5;124m'\u001b[39m) \u001b[38;5;28;01mas\u001b[39;00m f:\n\u001b[0;32m      8\u001b[0m         \u001b[38;5;28;01mreturn\u001b[39;00m f\u001b[38;5;241m.\u001b[39mread()\n\u001b[0;32m      9\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mFileNotFoundError\u001b[39;00m:\n",
      "File \u001b[1;32mc:\\Users\\zhoux\\anaconda3\\Lib\\site-packages\\IPython\\core\\interactiveshell.py:324\u001b[0m, in \u001b[0;36m_modified_open\u001b[1;34m(file, *args, **kwargs)\u001b[0m\n\u001b[0;32m    317\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m file \u001b[38;5;129;01min\u001b[39;00m {\u001b[38;5;241m0\u001b[39m, \u001b[38;5;241m1\u001b[39m, \u001b[38;5;241m2\u001b[39m}:\n\u001b[0;32m    318\u001b[0m     \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\n\u001b[0;32m    319\u001b[0m         \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mIPython won\u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mt let you open fd=\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mfile\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m by default \u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m    320\u001b[0m         \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mas it is likely to crash IPython. If you know what you are doing, \u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m    321\u001b[0m         \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124myou can use builtins\u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124m open.\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m    322\u001b[0m     )\n\u001b[1;32m--> 324\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m io_open(file, \u001b[38;5;241m*\u001b[39margs, \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwargs)\n",
      "\u001b[1;31mOSError\u001b[0m: [Errno 22] Invalid argument: '--f=c:\\\\Users\\\\zhoux\\\\AppData\\\\Roaming\\\\jupyter\\\\runtime\\\\kernel-v3dd56281ee2a79bb7a4dc5ec7e831f47e0494a325.json'"
     ]
    }
   ],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
